package com.example.t470p.facechecktickets.View;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.util.Xml;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.example.t470p.facechecktickets.R;


public class SelectGateActivity extends Activity {


    private ListView mListView;
    private String name;
    String[] from={"name","id"};              //这里是ListView显示内容每一列的列名
    int[] to={R.id.user_name,R.id.user_id};   //这里是ListView显示每一列对应的list_item中控件的id

    String[] userName={"散客闸机1","散客闸机2","散客闸机3","散客闸机4","散客闸机5","散客闸机6","散客闸机7","散客闸机8","散客闸机9","散客闸机10","散客闸机11","散客闸机12","散客闸机13","散客闸机14","散客闸机15","散客闸机16"}; //这里第一列所要显示的人名
    String[] userId={"A1001","B1002","X1003","W1004","D1002","W1003","1004","1002","1003","1004","1002","1003","1004","1002","1003","1004"};  //这里是人名对应的ID

    ArrayList<HashMap<String,String>> list=null;
    // HashMap<String,String> map=null;

    private String url;
    private String myname;
    private String mypwd;
    private String gateno;
    ArrayList listname = new ArrayList();
    ArrayList listno = new ArrayList();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_gate);
        mListView = (ListView)findViewById(R.id.MylistView);

        /*获取Intent中的Bundle对象*/
        Bundle bundle = this.getIntent().getExtras();
        url = bundle.getString("url");
        myname = bundle.getString("myname");
        mypwd = bundle.getString("mypwd");




        //透明度
/*        WindowManager.LayoutParams lp=getWindow().getAttributes();
        lp.alpha=1.0f;
        getWindow().setAttributes(lp);*/



        list=new ArrayList<HashMap<String,String>>();
        //将数据存放进ArrayList对象中，数据安排的结构是，ListView的一行数据对应一个HashMap对象，
        //HashMap对象，以列名作为键，以该列的值作为Value，将各列信息添加进map中，然后再把每一列对应
        //的map对象添加到ArrayList中

  /*       for(int i=0; i<16; i++){
            map=new HashMap<String,String>();       //为避免产生空指针异常，有几列就创建几个map对象
            map.put("id", userId[i]);
            map.put("name", userName[i]);
            list.add(map);
        }

        //创建一个SimpleAdapter对象
        SimpleAdapter adapter=new SimpleAdapter(this,list,R.layout.activity_selectgate,from,to);
        //调用ListActivity的setListAdapter方法，为ListView设置适配器
        //setListAdapter(adapter);
        mListView.setAdapter(adapter);*/

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                //获取被点击的item所对应的数据
                        HashMap<String, Object> map = (HashMap<String, Object>) parent.getItemAtPosition(position);
                //下面是你的其他事务逻辑
                System.out.println(position);
                name = map.get("id").toString();
                new AlertDialog.Builder(SelectGateActivity.this).setTitle("绑定手持机终端").setMessage(name)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                System.out.println(name);
                                gateno = name;
                                HttpURLBound();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
        HttpURL();
    }


    //==============================================================调用接口
    private void HttpURL() {
        new Thread(){
            public void run() {
                send();
            }
        }.start();

    }
    public boolean send() {
        try {
            // String sendUrl = "http://192.168.20.87:9090/SDWPK/checkTicketInterface/userLogin.do";
            String sendUrl = "http://" + url + "/checkTicketInterfaceTWO/getGateList.do";


            System.out.println(sendUrl);
            Map<String, String> map = new HashMap<String, String>();
            map.put("userName", myname);
            map.put("password", mypwd);
            String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");
            System.out.println(sign);

            //String sendDate = "userName=admin" + "&password=admin" + "&sign=" + sign;
            String sendDate = "userName=" + myname + "&password=" + mypwd + "&sign=" + sign;
            String result = sendPost(sendUrl, sendDate);
            System.out.println(result);

            if(result.equals("") || result.equals(null))
            {
                showToast("终端获取失败,请确认是否有足够的终端!");
                return true;
            }

            if (result.indexOf("<code>0</code>") > 0)
            {
                getxmlstr(result, "gateNo");
                getxmlnamestr(result, "gateName");

                mListView.post(new Runnable() {
                    @Override
                    public void run() {
                        HashMap<String,String> map=null;
                        for(int i=0; i<listname.size(); i++){
                            map=new HashMap<String,String>();       //为避免产生空指针异常，有几列就创建几个map对象
                            map.put("id", listno.get(i).toString());
                            map.put("name", listname.get(i).toString());
                            list.add(map);
                        }

                        //创建一个SimpleAdapter对象
                        SimpleAdapter adapter=new SimpleAdapter(SelectGateActivity.this,list,R.layout.activity_select_gate,from,to);
                        //调用ListActivity的setListAdapter方法，为ListView设置适配器
                        //setListAdapter(adapter);
                        mListView.setAdapter(adapter);

                    }
                });

            }
            else
            {
                String msg = getxmlstr(result, "message");
                System.out.println("test:" + msg);
                showToast(msg);
            }
        }
        catch (Exception e)
        {
            showToast("连接超时，请重试！");
        }
        return true;
    }

    /**
     * 验证消息是否为合法消息
     * @param params 参数数组
     * @param key 接口密钥
     * @return 验证结果
     */
    public static boolean verify(Map<String, String> params,String key) {

        String mysign = buildMysign(params,key);
        String sign = "";
        if(params.get("sign") != null) {sign = params.get("sign");}
        if (mysign.equals(sign)) {
            return true;
        } else {
            System.out.println("本地签名："+mysign + " 远程签名：" + sign);
            return false;
        }
    }

    /**
     * 生成签名结果
     * @param sArray 要签名的数组
     * @param key 通知密钥
     * @return 签名结果字符串
     */
    public static String buildMysign(Map<String, String> sArray,String key) {
        try {
            Map<String, String> result = paraFilter(sArray);
            String prestr = createLinkString(result); //把数组所有元素，按照“参数参数值”的模式拼接成字符串
            prestr = key + prestr; //把接口密钥+拼接后的字符串直接连接起来
            String mysign = md5(prestr);
            if (mysign != null) {
                mysign = mysign.toUpperCase();
                System.out.println(mysign);
            }
            return mysign;
        } catch (Exception e) {

        }
        return null;
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }


    /**
     * @param content
     * @param charset
     * @return
     * @throwsSignatureException
     * @throws UnsupportedEncodingException
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }

        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    /**
     * 除去数组中的空值和签名参数
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 把数组所有元素排序，并按照“参数参数值”的模式拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            prestr = prestr + key + value;
        }
        return prestr;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * @param sendUrl 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String sendUrl, String param) {
        try {
            // 发送POST请求
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(1000 * 10);
            conn.setReadTimeout(1000 * 20);

            conn.setRequestProperty("Content-Length", "" + param.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();
            out.close();

            // 获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            // 获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }
    private static String getString(byte[] b){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < b.length; i ++){
            sb.append(b[i]);
        }
        return sb.toString();
    }
    public String getxmlnamestr(String xml,String resultstr)
    {
        ByteArrayInputStream tInputStringStream = null;
        String returnstr = "";
        try
        {
            if (xml != null && !xml.trim().equals("")) {
                tInputStringStream = new ByteArrayInputStream(xml.getBytes());
            }
        }
        catch (Exception e) {
            return "";
        }
        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(tInputStringStream, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
                        // persons = new ArrayList<Person>();
                        break;
                    case XmlPullParser.START_TAG:// 开始元素事件
                        String name = parser.getName();
                        if (name.equalsIgnoreCase(resultstr)) {
                            returnstr = parser.nextText();
                            //System.out.println(returnstr);
                            listname.add(returnstr);
                        }
                        break;
                    case XmlPullParser.END_TAG:// 结束元素事件
                        break;
                }
                eventType = parser.next();
            }
            tInputStringStream.close();
            // return persons;

        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return  returnstr;
    }
    public String getxmlstr(String xml,String resultstr)
    {
        ByteArrayInputStream tInputStringStream = null;
        String returnstr = "";
        try
        {
            if (xml != null && !xml.trim().equals("")) {
                tInputStringStream = new ByteArrayInputStream(xml.getBytes());
            }
        }
        catch (Exception e) {
            return "";
        }
        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(tInputStringStream, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
                        // persons = new ArrayList<Person>();
                        break;
                    case XmlPullParser.START_TAG:// 开始元素事件
                        String name = parser.getName();
                        if (name.equalsIgnoreCase(resultstr)) {
                            returnstr = parser.nextText();
                            //System.out.println(returnstr);
                            listno.add(returnstr);
                        }
                        break;
                    case XmlPullParser.END_TAG:// 结束元素事件
                        break;
                }
                eventType = parser.next();
            }
            tInputStringStream.close();
            // return persons;

        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return  returnstr;
    }
    //======================================================================
    //非UI线程中显示Toast
    public void showToast(String msg){
        Looper.prepare();
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }


    /*
         * Function  :  保存数据到SharedPreferences对象中
         * Param     :  fileName保存数据的文件名；userName、userPswd保存的数据
         * Author    :  博客园-依旧淡然
         */
    public boolean saveDataToSharedPreferences(String fileName,String userName, String userDate) {
        boolean isSaveDataSuccess = false;           //存储数据成功标志位
        SharedPreferences sharedPreferences = this.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();    //创建SharedPreferences.Editor对象
        edit.putString(userName, userDate);        //存储数据
        isSaveDataSuccess = edit.commit();           //提交存储数据
        return isSaveDataSuccess;
    }
    /*
     * Function  :  从SharedPreferences对象中读取数据
     * Param     :  fileName保存数据的文件名
     * Author    :  博客园-依旧淡然
     */
    public String readDataFromSharedPreferences(String fileName,String userName) {
        Map<String, Object> map = new HashMap<String, Object>();            //Map对象，用于存储读取到的数据
        SharedPreferences sharedPreferences = this.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        String resrltstr = sharedPreferences.getString(userName, "");      //读取SharedPreferences对象中的数据
        return resrltstr;
    }

    private void HttpURLBound() {
        new Thread(){
            public void run() {
                sendBound();
            }
        }.start();

    }
    public boolean sendBound() {
        try {
            // String sendUrl = "http://192.168.20.87:9090/SDWPK/checkTicketInterface/userLogin.do";
            String sendUrl = "http://" + url + "/checkTicketInterfaceTWO/gateBound.do";

            System.out.println(sendUrl);
            Map<String, String> map = new HashMap<String, String>();
            map.put("userName", myname);
            map.put("password", mypwd);
            map.put("gateNo",gateno);
            String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");
            System.out.println(sign);

            //String sendDate = "userName=admin" + "&password=admin" + "&sign=" + sign;
            String sendDate = "userName="+ myname + "&password=" + mypwd +"&gateNo=" + gateno + "&sign=" + sign;
            String result = sendPost(sendUrl, sendDate);
            System.out.println(result);

            if (result.indexOf("<code>0</code>") > 0) {
                // saveDataToSharedPreferences("userInfo", "gateno", name);

                try
                {
                    //String configpath = "/storage/emulated/0/test.ini";
                    String configpath = getSDPath() + "/config.ini";
                    FileInputStream fis = null; // 读
                    OutputStream fos;
                    Properties pp;

                    pp = new Properties();
                    fis = new FileInputStream(configpath);
                    pp.load(fis);

                    gateno = pp.get("GateNO").toString();// 获取配置文件的Gps_device字段的信息，既它=号后面的数据

                    fos=new FileOutputStream(configpath);//加载读取文件流
                    pp.setProperty("GateNO", name);// 修改值
                    pp.store(fos, null);//修改值
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Intent intent = new Intent(SelectGateActivity.this, CheckActivity.class);
                Bundle bundle = new Bundle();
		                        /*字符、字符串、布尔、字节数组、浮点数等等，都可以传*/
                bundle.putString("url", url);
                bundle.putString("myname", myname);
                bundle.putString("mypwd", mypwd);
                bundle.putString("gateno", name);


                /*把bundle对象assign给Intent*/
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
                showToast("绑定成功！");
            } else {
                String msg = getxmlstr(result, "message");
                System.out.println("test:" + msg);
                showToast(msg);
            }
        }
        catch (Exception e)
        {
            showToast("请检查地址配置！");
            return  false;
        }
        return true;
    }

    /*
	* 获取SD卡路径
	*/
    public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if(sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

}


